import transfrom from './action/index.mjs';
import path from 'path';
import { writeFileSync, unlinkSync } from 'fs';
import { salt } from '../../utils/index.mjs';

const TEMP_FILE_NAME = '.traineddata';

export default async (program) => {
	program
		.command('start <target>', { isDefault: true })
		.helpOption('-h,--HELP')
		.option('-l --lang [char]', 'default transform language.', 'chi_sim')
		.option('-t --type [char]', 'generated file type.', '.txt')
		.action(async (target, self) => {
			try {
				const { lang, type } = self;
				const word = await transfrom(lang, target);
				const originName = path.basename(target).split('.')[0];
				const filename = originName + '.' + salt() + type;
				const resultSavedPath = path.resolve(process.cwd(), filename);
				const tempFile = path.resolve(process.cwd(), lang + TEMP_FILE_NAME);

				console.log('start write file...');
				writeFileSync(resultSavedPath, word);
				console.log('write file complete.');
				unlinkSync(tempFile);
				
				process.exit(0);
			} catch (error) {
				console.log(error);

				throw new Error('Write file Error');
			}
		});
};